package com.mallbook.model.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mallbook.model.exception.ServiceException;
import com.mallbook.model.pojo.Orders;
import com.mallbook.model.pojo.PageBean;
import com.mallbook.model.pojo.User;
import com.mallbook.model.mapper.OrdersMapper;
import com.mallbook.model.utils.MallDefaultConfig;
import com.mallbook.model.utils.MybatisUtils;

import java.util.List;

/**
 * @Author 宋明松
 * @Version V1.0.0
 * @Date 2022-06-27
 * 订单数据页类
 */
public class PageBeanOrders {
    /**
     * @param orders 条件
     * @param page   页数
     * @return
     */
    public static PageBean<Orders> getByPage(Orders orders, User user, int page) {
        OrdersMapper ordersMapper = MybatisUtils.getMappers(OrdersMapper.class);
        int pageSize = MallDefaultConfig.ORDER_PAGE_SIZE;
        // 根据条件，页码，分页大小，将PageBean中的属性依次设置
        PageBean<Orders> pageBean = new PageBean<>();
        // 根据时间降序
        PageHelper.orderBy("times desc");

        Page p = PageHelper.startPage(page, pageSize);
        List<Orders> data = null;
        if (orders == null) {
            try {
                // 查询所有有效订单
                data = ordersMapper.findOrders();
            } catch (
                    ServiceException e) {
                e.printStackTrace();
            }
        } else {
            try {
                // 条件查询
                data = ordersMapper.findOrdersByCondition(orders, user);
            } catch (
                    ServiceException e) {
                e.printStackTrace();
            }
        }
        pageBean.setData(data);
        pageBean.setCurrPage(page);
        pageBean.setCurrPageSize(data.size());
        pageBean.setPageSize(pageSize);
        pageBean.setTotalNums((int) p.getTotal());
        pageBean.setTotalPages(p.getPages());

        return pageBean;
    }
}
